package com.superhelper.app.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.CharArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.app.domain.AccessToken;
import com.superhelper.app.domain.Admin;
import com.superhelper.app.service.AdminService;
import com.superhelper.app.service.ShopService;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.service.RedisService;
import com.superhelper.common.utils.JsonHelper;

/**
 * 门店授权回调通知消息
 * 
 * @author Elson
 */
@Controller
public class AuthCallBackController {
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ShopService shopService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AdminService adminService;

    /**
     * 授权回调地址
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("api/eleme/auth")
    public String eleAuth(HttpServletRequest request) {
        String state = request.getParameter("state");
        String code = request.getParameter("code");
        log.info("[eleme]auth callback:{}", request.getQueryString());
        try {
            boolean res = shopService.elemeAuthCallBack(Integer.parseInt(state), code);
            log.info("[eleme]auth res:{}", res);
            if (res) {
                // response.getOutputStream().write(
                // "{\"data\":\"success\"}".getBytes("UTF-8"));
                return "auth_success";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("[auth]error:{}", e);
        }
        return "auth_error";
    }

    /**
     * 授权回调地址
     * 
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("api/mt/auth")
    public void mtAuth(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {

            InputStream instream = request.getInputStream();
            int i = request.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            Reader reader = new InputStreamReader(instream, "utf-8");
            CharArrayBuffer buffer = new CharArrayBuffer(i);
            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            String queryBody = buffer.toString();
            log.info("[mt]POST auth callback{}", queryBody);
            String auserId = request.getParameter("auserId");
            log.info("[mt]POST auth auserId:{}", auserId);
            if (queryBody.contains("appAuthToken")) {
                String params[] = queryBody.split("&");
                String shopId = null;
                String appAuthToken = null;
                for (String s : params) {
                    if (s.contains("ePoiId=")) {
                        shopId = s.replace("ePoiId=", "");
                    } else if (s.contains("appAuthToken=")) {
                        appAuthToken = s.replace("appAuthToken=", "");
                    }
                }
                if (StringUtils.isNotBlank(shopId)) {
                    boolean b = shopService.mtAuthCallBack(Integer.parseInt(auserId), shopId, appAuthToken);
                    if (b) {
                        response.getOutputStream().write("{\"data\":\"success\"}".getBytes("UTF-8"));
                    }
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 授权回调地址
     * 
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("api/bd/auth")
    public void bdAuth(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {

            InputStream instream = request.getInputStream();
            int i = request.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            Reader reader = new InputStreamReader(instream, "utf-8");
            CharArrayBuffer buffer = new CharArrayBuffer(i);
            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            String queryBody = buffer.toString();
            log.info("[mt]POST auth callback{}", queryBody);
            String auserId = request.getParameter("auserId");
            log.info("[mt]POST auth auserId:{}", auserId);
            if (queryBody.contains("appAuthToken")) {
                String params[] = queryBody.split("&");
                String shopId = null;
                String appAuthToken = null;
                for (String s : params) {
                    if (s.contains("ePoiId=")) {
                        shopId = s.replace("ePoiId=", "");
                    } else if (s.contains("appAuthToken=")) {
                        appAuthToken = s.replace("appAuthToken=", "");
                    }
                }
                if (StringUtils.isNotBlank(shopId)) {
                    boolean b = shopService.mtAuthCallBack(Integer.parseInt(auserId), shopId, appAuthToken);
                    if (b) {
                        response.getOutputStream().write("{\"data\":\"success\"}".getBytes("UTF-8"));
                    }
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 邀请码生成
     * 
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("code/create")
    public void codeCreate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String plfFrom = request.getParameter("plfFrom");
        String type = request.getParameter("type");
        String count = request.getParameter("count");
        if (StringUtils.isNoneBlank(count)) {
            for (int i = 0; i < Integer.parseInt(count); i++) {
                adminService.createCode(plfFrom, Integer.parseInt(type));
            }
            response.getOutputStream().write("{\"data\":\"success\"}".getBytes("UTF-8"));
        } else {
            response.getOutputStream().write("{\"data\":\"error params\"}".getBytes("UTF-8"));
        }
    }

    /**
     * 获取美团解绑链接
     */
    @RequestMapping("/url")
    @ResponseBody
    public String getMTAuthUrl(@RequestParam String phone) {
        Admin user = adminService.getAdminByUsername(phone);
        if (user != null) {
            List<AuserShop> shops = adminService.getAuserShopsByAuserId(user.getId());
            for (AuserShop a : shops) {
                if (a.getShop_type().equals(AuserShop.SHOP_MEITUAN)) {
                    String url = "https://open-erp.meituan.com/releasebinding?signKey=lj0ev7ovcjl1nq1p&businessId=2&appAuthToken=";
                    AccessToken token = JsonHelper.fromJson(a.getToken(), AccessToken.class);
                    return url + token.getToken();
                }
            }
        }
        return "error data";
    }
}